<?php
/**
 * Crc CMS
 *
 * @category   Crc
 * @package    Crc_Modules
 * @subpackage User
 * @author     Moldovan Calin <mcalin45@gmail.com>
 * @author     Vlad Razvan <razvanvlad1982@yahoo.com>
 * @copyright  Copyright (c) 2012
 * @version    $Id: adminController.php 89 2013-04-27 14:53:08Z mcalin45@gmail.com $
 */

/**
 * User admin controller
 *
 * @category   Crc
 * @package    Crc_Modules
 * @subpackage User
 * @author     Moldovan Calin <mcalin45@gmail.com>
 * @author     Vlad Razvan <razvanvlad1982@yahoo.com>
 * @copyright  Copyright (c) 2012
 */
class User_AdminController extends Crc_Controller_Action
{
    /**
     * @var Crc\Entity\RepositoryUserRepository
     */
    protected $userRepository;

    public function init()
    {
        parent::init();
        $this->userRepository = $this->entityManager->getRepository('\Crc\Entity\User');
    }

    /**
     * Display user list
     *
     * @return void
     */
    public function indexAction()
    {
        //\Zend_Debug::dump($this->getRequest()->getPost()); exit;
        $grid = new Crc\Grid('\Crc\Entity\User');
        //$grid->resetFilters();
        //$grid->resetColumns();

        if ($this->_getParam('quick_action')) {
            try {
                $grid->setQuickAction($this->_getParam('quick_action'), $this->_getParam('action_item'));
            } catch (Exception $e) {
                 Zend_Debug::dump($e);

            }
            $this->entityManager->flush();
            $this->_redirect('/user/admin/');
            exit;
        }

        if ($this->_getParam('do_filter') == 1) {
            if ($this->_getParam('reset_filter') == 2) {
                $grid->resetFilters();
            } else {
                $grid->resetFilters();
                $postData = $this->_getParam('filter');
                if (isset($postData['fields']) && is_array($postData['fields']) && count($postData['fields']) > 0) {
                    foreach($postData['fields'] as $filter) {
                        $grid->selectFilter(
                            $filter,
                            $postData['operators'][$filter],
                            $postData['values'][$filter]
                        );
                    }
                }
            }

            $selectedColumns = $this->_getParam('options');
            $selectedColumns = $selectedColumns['selected_columns'];
            $grid->setVisibleColumns($selectedColumns);

            $this->_redirect('/user/admin/');
        }
        if ($this->_getParam('set') == 'order') {
            $grid->setOrder($this->_getParam('field'));
            $this->_redirect('/user/admin/');
        }
        $queryBuilder = $grid->processGrid();

        //$grid->getQuickActions();
//        \Zend_Debug::dump($queryBuilder->__toString());
//        exit;

        //\Zend_Debug::dump($grid->getOrderBy());
        //\Zend_Debug::dump($grid->getInvisibleColumns());
        /*foreach($grid->getFilters() as $filter) {
            //\Zend_Debug::dump($filter);
            foreach($filter->getOperators() as $operator) {
                \Zend_Debug::dump($operator);
            }
        }*/
        //exit;


        $this->view->grid = $grid;

        $adapter = new Crc_Paginator_Adapter_Doctrine($queryBuilder);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam('page'));
        $paginator->setItemCountPerPage(10);
        $this->view->paginator = $paginator;
    }

    /**
     * Add a user
     *
     * @return void
     */
    public function addAction()
    {
        $form = new Crc_Form_Model(array(
            'model' => 'Crc\Entity\User',
            'ignoreColumns' => array('token', 'status')
        ));
        $user = new Crc\Entity\User();


        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $user = $form->save();
                $user->setStatus(1);
                $user->setPass($user->getPass());

                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/modules/user/views/scripts/email/');

                $html->assign('user', $user);
                $bodyText = $html->render('add.phtml');
                $mail = new Zend_Mail();
                $mail->setBodyHtml($bodyText);
                $mail->addTo($user->getEmail());
                $mail->setSubject('New account');
                $mail->send();

                $this->entityManager->flush();
                $this->_redirect('/user/admin/');
            }
        }

        $this->view->form = $form;
    }


     /**
     * Edit a user
     *
     * @return void
     */
    public function editAction()
    {
        $form = new Crc_Form_Model(array(
            'model' => 'Crc\Entity\User',
            'ignoreColumns' => array('pass', 'token', 'status')
        ));
        $itemId = $this->getRequest()->getParam('id');
        if ($itemId > 0) {
            $user = $this->userRepository->find($itemId);
            $form->setRecord($user);
        }


        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $user = $form->save();
                $this->entityManager->flush();
                $this->_redirect('/user/admin/');
            }
        }

        $this->view->form = $form;
    }

    /**
     * Delete a user
     *
     * @return void
     */
    public function deleteAction()
    {
        $itemId = $this->getRequest()->getParam('id');
        $user = $this->userRepository->find($itemId);
        $user->setStatus(Crc\Entity\User::STATUS_DELETED);
        $this->entityManager->flush();
        $this->_redirect('/user/admin/');
    }

    /**
     * Display roles
     *
     * @return void
     */
    public function rolesAction()
    {
        $grid = new Crc\Grid('\Crc\Entity\AclRole');
        if ($this->_getParam('quick_action')) {
            try {
                $grid->setQuickAction($this->_getParam('quick_action'), $this->_getParam('action_item'));
            } catch (Exception $e) {
                 Zend_Debug::dump($e);

            }
            $this->entityManager->flush();
            $this->_redirect('/user/admin/roles');
            exit;
        }

        if ($this->_getParam('do_filter') == 1) {
            if ($this->_getParam('reset_filter') == 2) {
                $grid->resetFilters();
            } else {
                $grid->resetFilters();
                $postData = $this->_getParam('filter');
                if (isset($postData['fields']) && is_array($postData['fields']) && count($postData['fields']) > 0) {
                    foreach($postData['fields'] as $filter) {
                        $grid->selectFilter(
                            $filter,
                            $postData['operators'][$filter],
                            $postData['values'][$filter]
                        );
                    }
                }
            }

            $selectedColumns = $this->_getParam('options');
            $selectedColumns = $selectedColumns['selected_columns'];
            $grid->setVisibleColumns($selectedColumns);

            $this->_redirect('/user/admin//roles');
        }
        if ($this->_getParam('set') == 'order') {
            $grid->setOrder($this->_getParam('field'));
            $this->_redirect('/user/admin/roles/');
        }
        $queryBuilder = $grid->processGrid();

        //$grid->getQuickActions();
//        \Zend_Debug::dump($queryBuilder->__toString());
//        exit;

        //\Zend_Debug::dump($grid->getOrderBy());
        //\Zend_Debug::dump($grid->getInvisibleColumns());
        /*foreach($grid->getFilters() as $filter) {
            //\Zend_Debug::dump($filter);
            foreach($filter->getOperators() as $operator) {
                \Zend_Debug::dump($operator);
            }
        }*/
        //exit;


        $this->view->grid = $grid;

        $adapter = new Crc_Paginator_Adapter_Doctrine($queryBuilder);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam('page'));
        $paginator->setItemCountPerPage(10);
        $this->view->paginator = $paginator;
    }

    /**
     * Save a role
     *
     * @return void
     */
    public function saveRoleAction()
    {
        $itemId = $this->getRequest()->getParam('id', null);
        $roles = new Application_Model_Collection_AclRole();
        if ($itemId > 0)
        {
            $role = $roles->find($itemId)->current();
        }
        else
        {
           $role = $roles->createRow();
        }

        $form = new Modules_User_Forms_AclRole();
        $form->setCustomValue('idParent', $itemId);
        $form->addSubForm('save');

        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $formData = $this->getRequest()->getPost('save');
                $role->setFromArray($formData);
                $role->save();
                $this->_redirect('/user/admin/roles');
            }
        }
        $form->populate($role->toArray());
        $this->view->form = $form;
    }

    /**
     * Save role's resources
     *
     * @return void
     */
    public function roleResourceAction()
    {
        $itemId = $this->getRequest()->getParam('id', null);
        $roles = new Application_Model_Collection_AclRole();
        $role = $roles->find($itemId)->current();
        $rights = new Application_Model_Collection_AclRight();
        if (!$role)
        {
            $this->_redirect('/user/admin/roles');
        }
        $form = new Modules_User_Forms_AclRole();
        $form->addSubForm('resource');

        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $formData = $this->getRequest()->getPost('resource');
                $rights->updateRoleRights($role, $formData);
                $this->_redirect('/user/admin/roles');
            }
        }

        $roleRigths = $rights->getRoleRights($role);
        $form->populate($roleRigths);
        $this->view->form = $form;
        $this->view->role = $role;
    }


    /**
     * Display resources
     *
     * @return void
     */
    public function resourcesAction()
    {
        $resources = new Application_Model_Collection_AclResource();
        $this->view->itemsList = $resources->fetchAll();
    }

    /**
     * Update a resource
     *
     * @return void
     */
    public function updateResourcesAction()
    {
        $resources = new Application_Model_Collection_AclResource();
        $resources->updateResources();
        $this->_redirect('/user/admin/resources');
    }

    /**
     * Save a resource
     *
     * @return void
     */
    public function saveResourceAction()
    {
        $itemId = $this->getRequest()->getParam('id', null);
        $resources = new Application_Model_Collection_AclResource();
        if ($itemId > 0)
        {
            $resource = $resources->find($itemId)->current();
        }
        else
        {
           $resource = $resources->createRow();
        }

        $form = new Modules_User_Forms_AclResource();
        $form->addSubForm('save');

        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $formData = $this->getRequest()->getPost('save');
                $resource->setFromArray($formData);
                $resource->save();
                $this->_redirect('/user/admin/resources');
            }
        }
        $form->populate($resource->toArray());
        $this->view->form = $form;
        $this->view->resource = $resource;
    }
}